package com.das.mechanic_webview.presenter.ground;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.ground.CarPropertiesBean;
import com.das.mechanic_base.bean.ground.UserCarInfoBean;
import com.das.mechanic_base.bean.main.AppointClueBean;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.bean.main.CarSelectBean;
import com.das.mechanic_base.bean.main.GiftBalanceBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.bean.main.UpadateReceBean;
import com.das.mechanic_base.bean.main.UpdateReceiveCarBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.ThreadPoolManager;
import com.das.mechanic_webview.contract.ground.X3GroundPushContract;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class X3GroundPushPresenter extends X3BasePresenter<X3GroundPushContract.View> implements X3GroundPushContract.Presenter {

    private UpdateReceiveCarBean carBean;

    @Override
    public void getCarList(long carOwnUserId) {

        NetWorkHttp.getApi().getCarList(carOwnUserId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<UserCarInfoBean>>() {
                    @Override
                    protected void onDone(List<UserCarInfoBean> carInfoBeans) {
                        mView.getMyCarList(carInfoBeans,carOwnUserId);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void saveAppointClue(AppointClueBean clueBean) {

        NetWorkHttp.getApi().saveForAppointClue(clueBean)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.saveAppointClueSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

//    @Override
//    public void requestVin(File file) {
//        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
//        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
//
//        NetWorkHttp.getApi().vinRecognition(body)
//                .compose(RxSchedulersHelper.defaultComposeRequest())
//                .compose(mView.bindToLife())
//                .subscribe(new HttpCallBack<String>() {
//                    @Override
//                    protected void onDone(String vin) {
//                        mView.getVin(vin);
//                    }
//
//                    @Override
//                    protected String LoadingMessage() {
//                        return null;
//                    }
//
//                    @Override
//                    protected void showError(String error) {
//
//                    }
//                });
//    }

    @Override
    public void getCreditPresentInfo(long carOwnerUserId) {
        NetWorkHttp.getApi().getCreditPresentInfo(carOwnerUserId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<GiftBalanceBean>() {
                    @Override
                    protected void onDone(GiftBalanceBean giftBalanceBean) {
                        mView.getCreditPresentInfoView(giftBalanceBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void requestCarNum(File carNum) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), carNum);
        try {
            String filename = URLEncoder.encode(carNum.getName(), "UTF-8");
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestBody);

            NetWorkHttp.getApi().requestCarNum(body)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<String>() {
                        @Override
                        protected void onDone(String carNum) {
                            mView.getCarNum(carNum);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void requestVin(File carVin) {
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), carVin);
            String  filename = URLEncoder.encode(carVin.getName(), "UTF-8");
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestBody);

            NetWorkHttp.getApi().vinRecognition(body)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<String>() {
                        @Override
                        protected void onDone(String vin) {
                            mView.getVin(vin);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void getCarMechanic(long carId) {

        NetWorkHttp.getApi().getCarForMechanic(carId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<CarPropertiesBean>() {
                    @Override
                    protected void onDone(CarPropertiesBean carPropertiesBean) {
                        mView.getCarForMechanic(carPropertiesBean,carId);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void downloadDropFile(String jsonUrl, String jsonPath) {
        if (!X3StringUtils.isEmpty(jsonUrl)) {
            new OkHttpClient().newCall(new Request.Builder().url(X3StringUtils.getImageUrl(jsonUrl)).build()).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull okhttp3.Call call, @NotNull Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        // 下载成功 但是回调失败
                        mView.downSuccess();
                        return;
                    } else {
                        ResponseBody body = response.body();
                        String source = body.string();
                        // 存储
                        X3FileUtils.writeIntoSDcard(jsonPath,source , "carMove.json");
                        mView.downSuccess();
                    }
                }

                @Override
                public void onFailure(@NotNull okhttp3.Call call, @NotNull IOException e) {
                    // 失败了也要回调
                    mView.downSuccess();
                }
            });
        } else {
            mView.downSuccess();
        }
    }

    @Override
    public void downCarJsonImageUrl(String imagePath, String imageUrl, String imageName) {
        ThreadPoolManager.getInstance().execute(() -> {
            try {
                X3FileUtils.saveFile(X3FileUtils.getImage(imageUrl), imageName, imagePath);
                mView.downSuccess();
            } catch (Exception e) {
                e.printStackTrace();
                mView.downSuccess();
            }
        });
    }

    @Override
    public void downCarImageUrl(String imagePath, String carUrl, String imageName) {
        ThreadPoolManager.getInstance().execute(() -> {
            try {
                X3FileUtils.saveFile(X3FileUtils.getImage(carUrl), imageName, imagePath);
                mView.downSuccess();
            } catch (Exception e) {
                e.printStackTrace();
                mView.downSuccess();
            }
        });
    }

    @Override
    public void saveOrUpdateOil(String selectData,long receiveBaseId) {
        if (X3StringUtils.isEmpty(selectData)) {
            return;
        }
        if (!X3StringUtils.isNum(selectData)) {
            return;
        }
        NetWorkHttp.getApi().saveOrUpdateOil(Integer.parseInt(selectData),receiveBaseId)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.saveOilSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void getReceiveBase(long receiveId) {
        NetWorkHttp.getApi().getReceiveBase(receiveId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<HomeMainCarBean>() {
                    @Override
                    protected void onDone(HomeMainCarBean mainCarBean) {
                        mView.getReceiveBase(mainCarBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void updateReceiveCar(CarSelectBean carSelectBean, String carNum) {
        if (carBean == null) {
            carBean = new UpdateReceiveCarBean();
        }
        //参数 车型
        if (!X3StringUtils.isEmpty(carSelectBean.getCarStyleName())) {
            carBean.setCarSeriesId(carSelectBean.getCarTypeId());
            String carStyleName = carSelectBean.getCarStyleName();
            String[] split = carStyleName.split("\\(");
            carBean.setCarSeriesName(split[0]);
        }
        //参数 车辆品牌
        if (!X3StringUtils.isEmpty(carSelectBean.getCarBrand())) {
            carBean.setCarBrandId(carSelectBean.getCarBrandId());
            carBean.setCarBrandName(carSelectBean.getCarBrand());
        }
        //参数年款
        if (!X3StringUtils.isEmpty(carSelectBean.getCarYear())) {
            carBean.setCarStyleId(carSelectBean.getCarStyleId());
            carBean.setCarStyleName(carSelectBean.getCarYear());
        }
        carBean.setCarVin(carSelectBean.getVin() + "");

        carBean.setColorId(carSelectBean.getColorId());

        carBean.setCarPicTempletId(carSelectBean.getCarPicTempletId());

        if (!X3StringUtils.isEmpty(carSelectBean.getCarMiles())) {
            carBean.setEstimateCurrentMiles(carSelectBean.getCarMiles());
        }
        if (!X3StringUtils.isEmpty(carSelectBean.getPerMiles())) {
            carBean.setPerMiles(carSelectBean.getPerMiles());
        }
        carBean.setCarProductionDate(carSelectBean.getCarProductionDate());

        if (!X3StringUtils.isEmpty(carNum)) {
            carBean.setCarNum(carNum);
        }

        if (!X3StringUtils.isEmpty(carSelectBean.getCarOwnerName())) {
            carBean.setCarOwnerName(carSelectBean.getCarOwnerName());
        }
        if (!X3StringUtils.isEmpty(carSelectBean.getGender())) {
            carBean.setGender(carSelectBean.getGender());
        }

        if (!X3StringUtils.isEmpty(carSelectBean.getMobile())) {
            carBean.setMobile(carSelectBean.getMobile());
        }

        if (carSelectBean.getCarTypeId() != 0) {
            carBean.setCarTypeId(carSelectBean.getCarTypeId());
        }
        if (!X3StringUtils.isEmpty(carSelectBean.getLastName())) {
            carBean.setLastName(carSelectBean.getLastName());
        }

        carBean.setChatroomBaseIdList(new ArrayList<>());

        carBean.setId(carSelectBean.getId());

        NetWorkHttp.getApi().updateReceiveCar(carBean)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<UpadateReceBean>() {
                    @Override
                    protected void onDone(UpadateReceBean upadateReceBean) {
                        mView.updateCarTypeSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void showCarPicAndColor(Map<String, Object> map,String carNum,long colorId,long carPicTempletId) {
        NetWorkHttp.getApi().showCarPicAndColor(map)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarPicAndColorBean>>() {
                    @Override
                    protected void onDone(List<CarPicAndColorBean> picList) {
                        mView.downCarPicSuccess(picList,carNum,colorId,carPicTempletId);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void uploadCarPic(long carId, String imgPath, String carNum) {
        File imgFile = new File(imgPath);
        if (!imgFile.exists()) {
            return;
        }
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);
            String  filename = URLEncoder.encode(imgFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            NetWorkHttp.getApi().createCarPic(carId,carNum,fileBody)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<CarPicAndColorBean>() {
                        @Override
                        protected void onDone(CarPicAndColorBean colorBean) {
                            mView.uploadCarPicSuccess(colorBean);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            mView.uploadCarPicSuccess(null);
                        }
                    });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void saveCommun(long id, String content) {

        NetWorkHttp.getApi().saveCommunicationMsg(id,content)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.saveCommunSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    public static Bitmap getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        InputStream inStream = conn.getInputStream();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            //return readStream(inStream);
            return BitmapFactory.decodeStream(inStream);

        }
        return null;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static boolean saveFile(Bitmap bm, String fileName, String path) {
        File jia = new File(path);
        if (!jia.exists()) {   //判断文件夹是否存在，不存在则创建
            jia.mkdirs();
        }

        File myCaptureFile = new File(jia.getAbsolutePath(), fileName);

        BufferedOutputStream bos = null;
        if (!myCaptureFile.exists()) {
            try {
                myCaptureFile.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }
}
